//
//  BEJobRequestController.swift
//  BEGlobalOiler
//
//  Created by KKING on 16/7/27.
//  Copyright © 2016年 Bullseye Energy pte ltd. All rights reserved.
//

import UIKit
import GoogleMaps
import SwiftyJSON

class BENewOrderController: UITableViewController {
    
    @IBOutlet weak var companyTf: UITextField!
    @IBOutlet weak var rigNameTf: UITextField!
    
    @IBOutlet weak var nameTf: UITextField!
    @IBOutlet weak var phoneTf: UITextField!
    
    //需要使用到pickerInputView的textField
    @IBOutlet weak var StartDateTf: UITextField!
    
    @IBOutlet weak var jobTypeTf: UITextField!
    @IBOutlet weak var equiTypeTf: UITextField!
    @IBOutlet weak var equiBrandTf: UITextField!
    @IBOutlet weak var equiModelTf: UITextField!
    @IBOutlet weak var serialNumTf: UITextField!
    @IBOutlet weak var equiIssueTv: UITextView!
    //此处仍然缺一个containerView的属性
    @IBOutlet weak var notesTf: UITextField!
    
    @IBOutlet weak var openMapBtn: UIButton!
    
    //公司id 场所id 设备id
    var companyId: String?
    var rigId: String?
    
    var equtypeId: String?
    var equBrandId: String?
    var equModelId: String?
    var equipmentId: String?
    var equipEquipId: String?
    var expectStartDateString: String?
    var expectEndDateString: String?
    
    private lazy var siteInputView: BESiteIPView = {
        let siteInputView = BESiteIPView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 216))
        return siteInputView
    }()
    
    private lazy var jobTypeInputView: BEJobTypeIPView = {
        let jobTypeInputView = BEJobTypeIPView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 216))
        return jobTypeInputView
    }()
    
    private lazy var equipTypeInputView: BEEquipTypeIPView = {
        let equipTypeInputView = BEEquipTypeIPView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 216))
        return equipTypeInputView
    }()
    
    private lazy var equipBrandInputView: BEEquipBrandIPView = {
        let equipBrandInputView = BEEquipBrandIPView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 216))
        return equipBrandInputView
    }()
    
    private lazy var equipmdlInputView: BEEquipmdlIPView = {
        let equipmdlInputView = BEEquipmdlIPView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 216))
        return equipmdlInputView
    }()
    
    private lazy var equipEquInputView: BEEquEquipIPView = {
        let equipEquInputView = BEEquEquipIPView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 216))
        return equipEquInputView
    }()
    
    private var datePicker: UIDatePicker = {
        let iputframe = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 216)
        let datepicker = UIDatePicker(frame: iputframe)
        datepicker.datePickerMode = .dateAndTime
        datepicker.locale = Locale.current
        return datepicker
    }()
    
    
    @objc private func datePickerChanged(datePicker: UIDatePicker){
        sharedDF.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        sharedDF.locale = Locale.current
        sharedDF.timeZone = TimeZone.current
        let StartDateString = sharedDF.string(from: datePicker.date)
        let index = StartDateString.index(StartDateString.startIndex, offsetBy: 16)
        StartDateTf.text = StartDateString.substring(to: index)
        
        expectStartDateString = StartDateString
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadEquipmentData()
        setupUI()
        
        //注册地图提交地理位置通知
        NotificationCenter.default.addObserver(self, selector: #selector(submitAddressAndDismissMap(notification:)), name: NSNotification.Name(rawValue: SubmitAddress), object: nil)
    }
    
    private func loadEquipmentData(){
        BENetworkTools.shareNetworkTool.getSiteBy(companyId: BEAccountModel.shareAccount()?.companyId ?? "") { (success, result, error) in
            guard let resultjson = result else {
                //                JFProgressHUD.showWithStatus(status: "您的网络不给力")
                return
            }
            if resultjson["success"] == true {
                let data = resultjson["result"].arrayObject as! [[String : AnyObject]]
                var siteData: [BESiteModel] = [BESiteModel]()
                for item in data{
                    let site = BESiteModel(dict: item)
                    //此处把数据添加到数组并设置给inputView
                    siteData.append(site)
                }
                //此处回到主线程把数据绑定给inputView
                DispatchQueue.main.async(execute: {
                    self.rigNameTf.text = "choose"
                    self.siteInputView.siteData = siteData
                })
                //                JFProgressHUD.showSuccessWithStatus(status: "confirm package success!")
            } else {
                //                JFProgressHUD.showInfoWithStatus(status: resultjson["message"].stringValue)
            }
        }
        
        //获取jobtype
        BENetworkTools.shareNetworkTool.getJobType { (success, result, error) in
            guard let resultjson = result else {
                //                JFProgressHUD.showWithStatus(status: "您的网络不给力")
                return
            }
            if resultjson["success"] == true {
                
                let data = resultjson["result"].arrayObject as! [[String : AnyObject]]
                var jobTypeData: [BEJobTypeModel] = [BEJobTypeModel]()
                for item in data{
                    let jobType = BEJobTypeModel(dict: item)
                    //此处把数据添加到数组并设置给inputView
                    jobTypeData.append(jobType)
                }
                //此处回到主线程把数据绑定给inputView
                DispatchQueue.main.async(execute: {
                    self.jobTypeTf.text = "choose"
                    self.jobTypeInputView.jobTypeData = jobTypeData
                })
                //                JFProgressHUD.showSuccessWithStatus(status: "confirm package success!")
            } else {
                //                JFProgressHUD.showInfoWithStatus(status: resultjson["message"].stringValue)
            }
        }
        
        //获取设备类型
        BENetworkTools.shareNetworkTool.getEquipmentType { (success, result, error) in
            guard let resultjson = result else {
                //                JFProgressHUD.showWithStatus(status: "您的网络不给力")
                return
            }
            if resultjson["success"] == true {
                let data = resultjson["result"].arrayObject as! [[String : AnyObject]]
                var equipTypeData: [BEEquipTypeModel] = [BEEquipTypeModel]()
                for item in data{
                    let equitType = BEEquipTypeModel(dict: item)
                    //此处把数据添加到数组并设置给inputView
                    equipTypeData.append(equitType)
                }
                //此处回到主线程把数据绑定给inputView
                DispatchQueue.main.async(execute: {
                    self.equiTypeTf.text = "choose"
                    self.equipTypeInputView.equipTypeData = equipTypeData
                })
                //                JFProgressHUD.showSuccessWithStatus(status: "confirm package success!")
            } else {
                //                JFProgressHUD.showInfoWithStatus(status: resultjson["message"].stringValue)
            }
        }
        
        //获取设备品牌
        BENetworkTools.shareNetworkTool.getEquipmentBrand { (success, result, error) in
            guard let resultjson = result else {
                //                JFProgressHUD.showWithStatus(status: "您的网络不给力")
                return
            }
            if resultjson["success"] == true {
                let data = resultjson["result"].arrayObject as! [[String : AnyObject]]
                var equipBrandData: [BEEquipBrandModel] = [BEEquipBrandModel]()
                for item in data{
                    let equipBrand = BEEquipBrandModel(dict: item)
                    //此处把数据添加到数组并设置给inputView
                    equipBrandData.append(equipBrand)
                }
                //此处回到主线程把数据绑定给inputView
                DispatchQueue.main.async(execute: {
                    self.equiBrandTf.text = "choose"
                    self.equipBrandInputView.equipBrandData = equipBrandData
                })
                //                JFProgressHUD.showSuccessWithStatus(status: "confirm package success!")
            } else {
                //                JFProgressHUD.showInfoWithStatus(status: resultjson["message"].stringValue)
            }
        }
    }
    
    
    private func setupUI(){
        view.backgroundColor = COLOR_ALL_BG
        
        //MARK: 设置输入视图 -- 时间 设备类型 设备品牌  / 缺油井选择以及型号选择 job type
        StartDateTf.inputView = datePicker
        StartDateTf.reloadInputViews()
        datePicker.addTarget(self, action: #selector(datePickerChanged(datePicker: )), for: .valueChanged)
        
        weak var weakSelf = self
        //site & rig 选择
        siteInputView.currentRowNumber = {
            (row) in
            if row == -1{
                weakSelf?.rigNameTf.text = "choose"
                weakSelf?.openMapBtn.titleLabel?.text = "map"
                weakSelf?.nameTf.text = ""
                weakSelf?.phoneTf.text = ""
                return
            }
            weakSelf?.rigNameTf.text = weakSelf?.siteInputView.siteData[row].name
            weakSelf?.openMapBtn.titleLabel?.text = weakSelf?.siteInputView.siteData[row].address
            weakSelf?.nameTf.text = weakSelf?.siteInputView.siteData[row].fullName
            weakSelf?.phoneTf.text = weakSelf?.siteInputView.siteData[row].mobile
            weakSelf?.rigId = weakSelf?.siteInputView.siteData[row].id
        }
        rigNameTf.inputView = siteInputView
        rigNameTf.reloadInputViews()
        
        //jobtype选择
        jobTypeInputView.currentRowNumber = {
            (row) in
            if row == -1{
                weakSelf?.jobTypeTf.text = "choose"
                return
            }
            weakSelf?.jobTypeTf.text = weakSelf?.jobTypeInputView.jobTypeData[row].name
        }
        jobTypeTf.inputView = jobTypeInputView
        jobTypeTf.reloadInputViews()
        
        //设备类型相关
        equipTypeInputView.currentRowNumber = {
            (row) in
            if row == -1{
                weakSelf?.equiTypeTf.text = "choose"
                return
            }
            weakSelf?.equiTypeTf.text = weakSelf?.equipTypeInputView.equipTypeData[row].name
            weakSelf?.equtypeId = weakSelf?.equipTypeInputView.equipTypeData[row].id
            weakSelf?.equiBrandTf.text = "choose"
            weakSelf?.equiModelTf.text = "choose"
            weakSelf?.serialNumTf.text = "choose"
        }
        equiTypeTf.inputView = equipTypeInputView
        equiTypeTf.reloadInputViews()
        
        //设备品牌相关
        equipBrandInputView.currentRowNumber = {
            (row) in
            if row == -1{
                weakSelf?.equiBrandTf.text = "choose"
                return
            }
            weakSelf?.equiBrandTf.text = weakSelf?.equipBrandInputView.equipBrandData[row].name
            weakSelf?.equBrandId = weakSelf?.equipBrandInputView.equipBrandData[row].id
            weakSelf?.equiModelTf.text = "choose"
            weakSelf?.serialNumTf.text = "choose"
        }
        equipBrandInputView.equmdlData = {
            (equmdlData) in
            weakSelf?.equipmdlInputView.equipMdlData = equmdlData
        }
        equiBrandTf.inputView = equipBrandInputView
        equiBrandTf.reloadInputViews()
        
        //设备型号相关
        equipmdlInputView.currentRowNumber = {
            (row) in
            if row == -1{
                weakSelf?.equiModelTf.text = "choose"
                return
            }
            if weakSelf?.equipmdlInputView.equipMdlData.count == 0 {
                return
            }
            weakSelf?.equiModelTf.text = weakSelf?.equipmdlInputView.equipMdlData[row].name
            weakSelf?.equipmentId = weakSelf?.equipmdlInputView.equipMdlData[row].id
            weakSelf?.serialNumTf.text = "choose"
        }
        equipmdlInputView.equEquipData = {
            (equEquipData) in
            weakSelf?.equipEquInputView.equipEquipData = equEquipData
        }
        equiModelTf.inputView = equipmdlInputView
        equiModelTf.reloadInputViews()
        
        
        //TODO: 此处需增加选择完成回调
        equipEquInputView.currentRowNumber = {
            (row) in
            if row == -1{
                weakSelf?.serialNumTf.text = "choose"
                return
            }
            if weakSelf?.equipEquInputView.equipEquipData.count == 0 {
                return
            }
            weakSelf?.serialNumTf.text = weakSelf?.equipEquInputView.equipEquipData[row].name
            weakSelf?.equipEquipId = weakSelf?.equipEquInputView.equipEquipData[row].id
        }
        serialNumTf.inputView = equipEquInputView
        serialNumTf.reloadInputViews()
        
        //进来此页面自动填充
        //        nameTf.text = BEAccountModel.shareAccount()?.userRealname
        companyTf.text = BEAccountModel.shareAccount()?.companyName
        //        phoneTf.text = BEAccountModel.shareAccount()?.phone
    }
    
    @objc func submitAddressAndDismissMap(notification: NSNotification){
        guard let address = notification.userInfo!["address"] as? String else{
            return
        }
        openMapBtn.titleLabel?.text = address
        //        performSelector(inBackground: #selector(googleMapsVc.popSelf), with: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @IBAction func saveBtnDidClick(button: UIButton) {
        if companyTf.text == "" && rigNameTf.text == "" && nameTf.text == "" && phoneTf.text == "" && StartDateTf.text == "" && jobTypeTf.text == "" && equiTypeTf.text == "" && equiBrandTf.text == "" && equiModelTf.text == "" && serialNumTf.text == "" && notesTf.text == ""{
            
            showAlert(title: "warning", message: "Null cannot be saved", cancleTitle: "Cancle", doneTitle: "Continue to write")
            return
        }
        JFProgressHUD.showWithStatus(status: "Please wait a moment...")
        createNewOrder(issubmit: false) { (success, tip) in
            if success {
                JFProgressHUD.showSuccessWithStatus(status: tip)
            } else {
                JFProgressHUD.showInfoWithStatus(status: tip)
            }
        }
    }
    
    @IBAction func submitBtnDidClick(button: UIButton) {
        
        if companyTf.text == "" || rigNameTf.text == "" || nameTf.text == "" || phoneTf.text == "" || StartDateTf.text == "" || jobTypeTf.text == "" || equiTypeTf.text == "" || equiBrandTf.text == "" || equiModelTf.text == "" || serialNumTf.text == "" {
            
            let alertVC = UIAlertController(title: "warning", message: "Please complete your order,and you can save it!", preferredStyle: .alert)
            let cancleAction = UIAlertAction(title: "Save", style: .default) { (_) in
                self.saveBtnDidClick(button: UIButton())
            }
            let doneAction = UIAlertAction(title: "Continue to write", style: .default) { (_) in
            }
            alertVC.addAction(cancleAction)
            alertVC.addAction(doneAction)
            UIApplication.shared.keyWindow?.rootViewController!.present(alertVC, animated: true, completion: nil)
            return
        }
        
        JFProgressHUD.showWithStatus(status: "Is submitting...")
        createNewOrder(issubmit: true) { (success, tip) in
            if success {
                JFProgressHUD.showSuccessWithStatus(status: tip)
            } else {
                JFProgressHUD.showInfoWithStatus(status: tip)
            }
        }
    }
    
    
    //此处增加创建订单的网络请求
    func createNewOrder(issubmit: Bool,finished: @escaping (_ success: Bool, _ tip: String) -> ()) {
        
        var parametersDesub: [String : AnyObject] = [
            "companyId": BEAccountModel.shareAccount()?.companyId as AnyObject? ?? "" as AnyObject,
            "rigId":  rigId as AnyObject? ?? "" as AnyObject,
            "equipmentId": equipEquipId as AnyObject? ?? "" as AnyObject,
            
            //txt的值
            "expectStartTime": expectStartDateString as AnyObject? ?? "" as AnyObject,
            //此处是segm选择的值
            "workPlace": 1 as AnyObject,
            
            //工作类型 jobtype
            "workType": 1 as AnyObject,
            
            "issueDesc": equiIssueTv.text as AnyObject? ?? "" as AnyObject,
            "currency": 1 as AnyObject,
            "photoNotes": notesTf.text as AnyObject? ?? "" as AnyObject,
            
            //不需要填写的 默认的内容
            "payType": 1 as AnyObject,
            "payTerm": 1 as AnyObject,
            ]
        /*
         {
         "companyId": 0,
         "rigId": 0,
         "equipmentId": 0,
         
         "expectEndTime": "2016-10-11T09:19:00.100Z",
         "workPlace": 0,
         "orderTime": "2016-10-11T09:19:00.100Z",
         "workType": 0,
         "issueDesc": "string",
         "currency": 0,
         "photoNotes": "string",
         "payType": 0,
         "payTerm": 0,
         
         "type": 0,
         "model": 0,
         "brandId": 0,
         "serialNumber": "string",
         "typeName": "string",
         "modelName": "string",
         "brandName": "string",
         
         "submit": false
         }
         */
        
        parametersDesub["submit"] = "\(issubmit)" as AnyObject?
        //        print("请求的参数是" + "\(parametersDesub)")
        
        BENetworkTools.shareNetworkTool.createNewOrder(parameters: parametersDesub) { (success, result, error) in
            guard let resultjson = result else {
                finished(false, "Network fault!")
                return
            }
            //            print(resultjson)
            if resultjson["success"] == true {
                
                finished(true, "Order Create Success!")
            } else {
                finished(false, resultjson["message"].stringValue)
            }
        }
    }
    
    @IBAction func openGoogleMapBtnClick(sender: AnyObject) {
        
        //此处增加定位判断,如果可以定位则跳转到mapcontroller.不可以跳转则提示打开定位服务.
        //极端情况:(如果当前设备没有GPS模块则会导致程序崩溃)
        //增加定位服务的判断
        let status = CLLocationManager.authorizationStatus()
        if (CLLocationManager.locationServicesEnabled() == true) && (status != .denied) && (status != .restricted) {
            navigationController?.pushViewController(BEGoogleMapsViewController(), animated: true)
        }else{
            let alertVC = UIAlertController(title: "提示", message: "请去设置中打开定位服务并重新打开此页面", preferredStyle: .alert)
            
            let cancleAction = UIAlertAction(title: "Cancle", style: .cancel, handler: nil)
            let doneAction = UIAlertAction(title: "OK", style: .default) { (_) in
                //跳转到设置中 打开定位服务
                UIApplication.shared.openURL(NSURL(string: "prefs:root=LOCATION_SERVICES")! as URL)
            }
            
            alertVC.addAction(cancleAction)
            alertVC.addAction(doneAction)
            
            self.present(alertVC, animated: true, completion: nil)
        }
    }
}

